package cn.woowc.through.loader;

import cn.woowc.through.listener.event.ThroughApplicationEvent;
import cn.woowc.through.listener.event.ThroughDingUrlInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.ClassPathResource;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Objects;

/**
 * @version V1.0.0
 * @ClassName: {@link DingAfterInitLoader}
 * @Description: Ding 初始化后加载
 * @author: Lanzhou
 * @date: 2021/4/29 17:08
 * @Copyright:2020 All rights reserved.
 */
@Slf4j
@ConditionalOnProperty(name = {"through.adopt"}, havingValue = "ding")
public class DingAfterInitLoader extends RunBatInitLoader {

    /**
     * 子域名
     */
    @Value("${through.sub-domain}")
    private String subDomain;

    @Value("${server.port:8080}")
    private int port;

    private static final String OK = "OK";

    private static final String[] ENV_RESOURCE = {"cmd/ding.exe", "cmd/ding.cfg"};

    @Resource
    private ApplicationContext context;

    @PostConstruct
    public void init() {
        try {
            createRunEnv(ENV_RESOURCE);
            String url = batBash();
            if (null != url) {
                ThroughDingUrlInfo info = new ThroughDingUrlInfo(url);
                context.publishEvent(new ThroughApplicationEvent(info));
            }
        } catch (IOException e) {
            log.error("初始加载失败, 请检查参数配置", e);
        }
    }


    /**
     * 执行命令并返回域名地址
     *
     * @return
     * @throws IOException
     */
    private String batBash() throws IOException {
        // 把你的bat脚本路径写在这里
        ClassPathResource classPathResource = new ClassPathResource("cmd/ding.exe");
        boolean exists = classPathResource.exists();
        if (exists) {
            File file = classPathResource.getFile();
            String path = file.getAbsolutePath();
            String name = file.getName();
            // 获取盘符
            String pathAddr = path.split(":")[0];
            // 进入所在的文件位置
            String pathInfo = path.replace(name, "");
            String order = pathAddr + "\n" +
                    "CD " + pathInfo + "\n" +
                    "cmd.exe /c start ./ding -config=./ding.cfg -subdomain=" + subDomain + " " + port;
            String batPath = pathInfo + "ding-run.bat";
            // 文件在的話刪除
            File batFile = new File(batPath);
            if (batFile.exists()) {
                boolean delete = batFile.delete();
                log.debug("清除缓存文件 [ {} ] 执行, 状态: [ {} ]", batPath, delete);
            }
            createRunBat(batPath, order);
            // 执行cmd
            String execBat = execBat(batPath);
            if (Objects.equals(OK, execBat)) {
                return subDomain + ".vaiwan.com";
            }
        }
        return null;
    }


}
